package com.carbon.assets.controller;

import com.carbon.domain.assets.vo.MethodologyUploadParam;
import com.carbon.assets.repository.MethodologyRepository;
import com.carbon.assets.service.CarbonMethodologyService;
import com.carbon.assets.param.CarbonMethodologyQueryParam;
import com.carbon.assets.service.SynMethodologyContentService;
import com.carbon.assets.vo.CarbonMethodologyQueryVo;
import com.carbon.assets.entity.CarbonMethodology;
import com.carbon.assets.entity.CarbonMethodologyContent;
import com.carbon.assets.common.BaseController;
import com.carbon.assets.vo.CarbonMethodologySelectVo;
import com.carbon.domain.common.ApiResult;
import com.carbon.common.api.Paging;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * <p>
 * 碳减排方法学 前端控制器
 * </p>
 *
 * @author Li Jun
 * @since 2021-07-31
 */
@Slf4j
@RestController
@RequestMapping("/carbonMethodology")
@Api(value = "碳减排方法学模块", tags = {"碳减排方法学模块"})
public class CarbonMethodologyController extends BaseController {

    @Autowired
    private CarbonMethodologyService carbonMethodologyService;

    @Autowired
    private MethodologyRepository methodologyRepository;

    @Autowired
    private SynMethodologyContentService synMethodologyContentService;

    /**
     * 添加碳减排方法学
     */
    @PostMapping("/upload")
    @ApiOperation(value = "添加碳减排方法学",notes = "添加碳减排方法学")
    public ApiResult<Boolean> addCarbonMethodology(@Valid @RequestBody MethodologyUploadParam param) {
        CarbonMethodology query = carbonMethodologyService.lambdaQuery()
                .select(CarbonMethodology.class,i->i.getProperty().equals("created_time")||i.getProperty().equals("updated_time"))
                .eq(CarbonMethodology::getDictCode,param.getDictCode())
                .one();
        if(query!=null)
        {
            return ApiResult.fail("字典编码已存在");
        }
        try {
            carbonMethodologyService.addCarbonMethodology(param);
        }catch (DataIntegrityViolationException e)
        {
            return ApiResult.fail("请先添加对应的字段编码");
        }

        return ApiResult.ok();
    }

    /**
     * 修改碳减排方法学
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改碳减排方法学",notes = "修改碳减排方法学")
    public ApiResult<Boolean> updateCarbonMethodology(@Valid @RequestBody CarbonMethodology carbonMethodology) {
        System.out.println(carbonMethodology);
        boolean flag = carbonMethodologyService.updateCarbonMethodology(carbonMethodology);
        return ApiResult.result(flag);
    }

    /**
     * 获取碳减排方法学
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "查看碳减排方法学",notes = "查看碳减排方法学")
    public ApiResult<CarbonMethodologyQueryVo> getCarbonMethodology(@PathVariable String id) {
        CarbonMethodologyQueryVo carbonMethodologyQueryVo = carbonMethodologyService.getCarbonMethodologyById(id);
        return ApiResult.ok(carbonMethodologyQueryVo);
    }

    /**
     * 碳减排方法学分页列表
     */
    @PostMapping("/getPageList")
    @ApiOperation(value = "碳减排方法学分页列表",notes = "碳减排方法学分页列表")
    public ApiResult<Paging<CarbonMethodologyQueryVo>> getCarbonMethodologyPageList(@Valid @RequestBody(required = false) CarbonMethodologyQueryParam carbonMethodologyQueryParam) {
        Paging<CarbonMethodologyQueryVo> paging = carbonMethodologyService.getCarbonMethodologyPageList(carbonMethodologyQueryParam);
        return ApiResult.ok(paging);
    }

    /**
     * 获取碳减排方法学列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "方法学下拉列表",notes = "方法学下拉列表")
    public ApiResult<List<CarbonMethodologySelectVo>> getCarbonMethodologyList() {
        return ApiResult.ok(carbonMethodologyService.getCarbonMethodologyList());
    }

    @GetMapping("/gbn/{name}")
    public CarbonMethodology getCarbonMethodologyByName(@PathVariable String name) {
        System.out.println(name);
        try {
            return carbonMethodologyService.getCarbonMethodologyByName(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除碳减排方法学
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除碳减排方法学",notes = "删除碳减排方法学")
    public ApiResult<Boolean> deleteCarbonMethodology(@PathVariable String id) {
        try {
            boolean flag = carbonMethodologyService.removeById(id);
            if (flag) {
                // 同时从Elasticsearch中删除
                try {
                    methodologyRepository.deleteById(id);
                    log.info("成功从Elasticsearch中删除方法学: {}", id);
                } catch (Exception e) {
                    log.warn("从Elasticsearch中删除方法学失败: {}, 错误: {}", id, e.getMessage());
                }
            }
            return ApiResult.result(flag);
        } catch (Exception e) {
            log.error("删除方法学失败: {}", e.getMessage());
            return ApiResult.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 同步方法学数据到Elasticsearch
     */
    @PostMapping("/syncToEs")
    @ApiOperation(value = "同步方法学数据到Elasticsearch",notes = "同步方法学数据到Elasticsearch")
    public ApiResult<String> syncToEs() {
        try {
            log.info("开始同步方法学数据到Elasticsearch");
            
            // 获取所有方法学数据 - 使用分页查询获取完整的方法学信息
            CarbonMethodologyQueryParam param = new CarbonMethodologyQueryParam();
            param.setSize(10000); // 设置一个较大的页面大小来获取所有数据
            Paging<CarbonMethodologyQueryVo> paging = carbonMethodologyService.getCarbonMethodologyPageList(param);
            List<CarbonMethodologyQueryVo> methodologies = paging.getRecords();
            
            int successCount = 0;
            int failCount = 0;
            
            for (CarbonMethodologyQueryVo methodology : methodologies) {
                try {
                    // 创建CarbonMethodologyContent对象
                    CarbonMethodologyContent content = new CarbonMethodologyContent();
                    content.setId(methodology.getId());
                    content.setName(methodology.getName());
                    content.setMethodCode(methodology.getMethodCode());
                    content.setDictCode(methodology.getDictCode());
                    content.setCertificationCriteria(methodology.getCertificationCriteria());
                    content.setCertificationCriteriaName(methodology.getCertificationCriteriaName());
                    content.setSourceFileUrl(methodology.getSourceFileUrl());
                    content.setCdmCode(methodology.getCdmCode());
                    content.setTranslateVersion(methodology.getTranslateVersion());
                    content.setFilingBatch(methodology.getFilingBatch());
                    content.setFieldCode(methodology.getFieldCode());
                    content.setFieldCodeName(methodology.getFieldCodeName());
                    content.setFieldChildCode(methodology.getFieldChildCode());
                    content.setFieldChildCodeName(methodology.getFieldChildCodeName());
                    content.setIndustryCode(methodology.getIndustryCode());
                    content.setIndustryCodeName(methodology.getIndustryCodeName());
                    content.setStatusCode(methodology.getStatusCode());
                    content.setTypeCode(methodology.getTypeCode());
                    
                    // 保存到Elasticsearch
                    methodologyRepository.save(content);
                    successCount++;
                    log.info("成功同步方法学: {}", methodology.getName());
                } catch (Exception e) {
                    failCount++;
                    log.error("同步方法学失败: {}, 错误: {}", methodology.getName(), e.getMessage());
                }
            }
            
            log.info("方法学数据同步完成，成功: {}, 失败: {}", successCount, failCount);
            return ApiResult.ok("同步完成，成功: " + successCount + ", 失败: " + failCount);
            
        } catch (Exception e) {
            log.error("同步方法学数据到Elasticsearch失败", e);
            return ApiResult.fail("同步失败: " + e.getMessage());
        }
    }
}
